<template>
  <div class="header-search" :class="{ show: show }">
    <svg-icon
      class-name="search-icon"
      icon-class="search"
      @click.stop="showSearch"
    />
    <el-select
      class="header-search-select"
      ref="headerSearchSelect"
      v-model="search"
      :remote-method="querySearch"
      filterable
      default-first-option
      remote
      placeholder="Search"
      @change="change"
    >
      <el-option
        v-for="item in options"
        :key="item.path"
        :value="item"
        :label="item.title.join(' > ')"
      />
    </el-select>
  </div>
</template>

<script>
// fuse is a lightweight fuzzy-search module make search results more in line with expectations
// fuse是一个轻量级的模糊搜索模块使搜索结果更符合预期
import Fuse from 'fuse.js'
import path from 'path'

export default {
  name: 'HeaderSearch',
  data() {
    return {
      fuse: undefined,
      search: '',
      searchPool: [],
      options: [],
      show: false,
    }
  },

  computed: {
    routes() {
      return this.$store.getters.permission_routes
    },
  },

  watch: {
    routes() {
      this.searchPool = this.generateRoutes(this.routes)
    },
    searchPool(list) {
      this.initFuse(list)
    },
    show: function(value) {
      if (value) {
        document.body.addEventListener('click', this.close)
      } else {
        document.body.removeEventListener('click', this.close)
      }
    },
  },

  mounted() {
    this.searchPool = this.generateRoutes(this.routes)
  },

  methods: {
    showSearch() {
      this.show = !this.show
      if (this.show) {
        this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.focus()
      }
    },

    close() {
      this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.blur()
      this.options = []
      this.show = false
    },

    generateRoutes(routes, basePath = '/', prefixTitle = []) {
      let res = []
      for (const router of routes) {
        // skip hidden router  跳过隐藏的路由
        if (router.hidden) {
          continue
        }

        const data = {
          path: path.resolve(basePath, router.path),
          title: [...prefixTitle],
        }

        if (router.meta && router.meta.title) {
          data.title = [...data.title, router.meta.title]
          if (router.redirect !== 'noRedirect') {
            // only push the routes with title
            // special case: need to exclude parent router without redirect
            // 特殊情况：需要在不重定向的情况下排除父路由器
            res.push(data)
          }
        }

        // recursive child routes 子路由的处理
        if (router.children) {
          const tempRoutes = this.generateRoutes(
            router.children,
            data.path,
            data.title
          )
          if (tempRoutes.length >= 1) {
            res = [...res, ...tempRoutes]
          }
        }
      }
      return res
    },

    initFuse(list) {
      this.fuse = new Fuse(list, {
        shouldSort: true, // 是否按分数对结果列表进行排序
        threshold: 0.4, // 匹配经度 0 精度高 1精度低
        location: 0, // 定位文本具体位置
        distance: 100,
        maxPatternLength: 32, // 最大输入字符长度匹配
        minMatchCharLength: 1, // 最小输入字符长度匹配
        keys: [
          {
            name: 'title',
            weight: 0.7,
          },
          {
            name: 'path',
            weight: 0.3,
          },
        ],
      })
    },

    // 搜索输入框 选择下拉的地址筛选方法
    querySearch(query) {
      // query 是输入框的值
      // console.log(query)
      if (query !== '') {
        this.options = this.fuse.search(query)
        // console.log(this.options)
      } else {
        this.options = []
      }
    },

    // 搜索框 选择地址后的方法
    change(val) {
      this.$router.push(val.path)
      this.search = ''
      this.options = []
      this.$nextTick(() => {
        this.show = false
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.header-search {
  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }

  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }

  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    ::v-deep .el-input__inner {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      vertical-align: middle;
    }

    /* 搜索框获取焦点时 底部边框 */
    ::v-deep .is-focus .el-input__inner {
      border-bottom: 1px solid #d9d9d9;
    }
  }
}

.el-select-dropdown__item.selected {
  color: #606266;
  font-weight: normal;
}
</style>
